<template>
  <div class="register-container">
    <el-card class="register-card" shadow="hover">
      <!-- 页面标题 -->
      <div class="register-header">
        <h2 class="register-title">
          <el-icon class="title-icon">
            <UserFilled />
          </el-icon>
          用户注册
        </h2>
        <p class="register-subtitle">请填写以下信息完成注册</p>
      </div>

      <!-- 步骤条 -->
      <el-steps
        class="register-steps"
        :active="active"
        finish-status="success"
        align-center
      >
        <el-step title="填写信息" />
        <el-step title="邮箱验证" />
        <el-step title="注册完成" />
      </el-steps>

      <!-- 注册表单 -->
      <el-form
        ref="registerFormRef"
        :model="registerData"
        :rules="registerData.rules"
        label-width="120px"
        class="register-form"
        size="large"
      >
        <!-- 基本信息区域 -->
        <el-divider content-position="left">
          <el-icon>
            <User />
          </el-icon>
          基本信息
        </el-divider>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="学号" prop="stuNum">
              <el-input
                v-model="registerData.stuNum"
                placeholder="请输入12位学号"
                prefix-icon="Postcard"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名" prop="stuName">
              <el-input
                v-model="registerData.stuName"
                placeholder="请输入真实姓名"
                prefix-icon="User"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系方式" prop="phone">
              <el-input
                v-model="registerData.phone"
                placeholder="请输入11位手机号码"
                prefix-icon="Phone"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="学院专业" prop="schoolMajor">
              <el-cascader
                v-model="registerData.schoolMajor"
                placeholder="请选择学院专业"
                style="width: 100%"
                :options="data.SchoolMajorOptions"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="研究方向" prop="domain">
          <el-cascader
            v-model="registerData.domain"
            :options="data.DomainOptions"
            placeholder="请选择研究方向"
            style="width: 100%"
            clearable
          />
        </el-form-item>

        <!-- 账户安全区域 -->
        <el-divider content-position="left">
          <el-icon>
            <Lock />
          </el-icon>
          账户安全
        </el-divider>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="密码" prop="pass">
              <el-input
                type="password"
                v-model="registerData.pass"
                placeholder="6-20位，包含字母和数字"
                prefix-icon="Lock"
                show-password
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="确认密码" prop="pass2">
              <el-input
                type="password"
                v-model="registerData.pass2"
                placeholder="请再次输入密码"
                prefix-icon="Lock"
                show-password
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 邮箱验证区域 -->
        <el-divider content-position="left">
          <el-icon>
            <Message />
          </el-icon>
          邮箱验证
        </el-divider>

        <el-form-item label="邮箱地址" prop="email">
          <el-autocomplete
            v-model="registerData.email"
            :fetch-suggestions="querySearch"
            placeholder="请输入邮箱地址"
            prefix-icon="Message"
            style="width: 100%"
            clearable
            @select="handleSelect"
            @change="myWatch(registerFormRef)"
          >
            <template #default="{ item }">
              <div class="email-suggestion">{{ item }}</div>
            </template>
          </el-autocomplete>
        </el-form-item>

        <el-form-item label="验证码">
          <div class="verification-code-container">
            <el-input
              v-model="registerData.emailRender"
              placeholder="请输入验证码"
              prefix-icon="Key"
              class="verification-input"
              clearable
            />
            <el-button
              type="primary"
              :disabled="registerData.setSendStatus"
              @click="uploadCode($event, registerFormRef)"
              class="send-code-btn"
              :icon="Message"
            >
              {{ registerData.text }}
            </el-button>
          </div>
        </el-form-item>

        <!-- 操作按钮 -->
        <el-form-item class="form-actions">
          <el-button
            type="primary"
            size="large"
            @click="submitForm(registerFormRef)"
            :loading="loading"
            class="submit-btn"
            :icon="Check"
          >
            {{ loading ? '注册中...' : '立即注册' }}
          </el-button>
          <el-button
            size="large"
            @click="resetForm(registerFormRef)"
            class="reset-btn"
            :icon="RefreshLeft"
          >
            重置表单
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 登录链接 -->
      <div class="login-link">
        <span class="login-text">已有账号？</span>
        <el-button type="text" class="login-btn" @click="goToLogin">
          立即登录
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup >
import { onMounted, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import {
  UserFilled,
  User,
  Lock,
  Message,
  Check,
  RefreshLeft,
  School,
} from '@element-plus/icons-vue'
import { Post, postCode } from '../../api/myApi'
import base from '../../api/base'
import md5 from 'js-md5'
import router from '../../router'
import { initUserMajor, registerUser } from '@/views/login/user'

const data = reactive({
  SchoolMajorOptions: [],
  DomainOptions: [],
})
onMounted(() => {
  initUserMajor().then(res => {
    console.log('initUserMajor', res)
    data.SchoolMajorOptions = res.data.schoolmajor
    data.DomainOptions = res.data.domain
  })
})
const active = ref(0)
const registerFormRef = ref(null)
const loading = ref(false)
const registerData = reactive({
  stuNum: '',
  stuName: '',
  pass: '',
  pass2: '',
  email: '',
  emailRender: '',
  schoolMajor: [],
  phone: '',
  domain: '',
  text: '发送验证码',
  setSendStatus: false,
  rules: {
    stuNum: [{ validator: validatorId, required: true, trigger: 'blur' }],
    stuName: [{ validator: validatorName, required: true, trigger: 'blur' }],
    phone: [{ validator: validatorIdPhone, required: true, trigger: 'blur' }],
    schoolMajor: [{ required: true, trigger: 'blur' }],
    domain: [{ required: true, trigger: 'blur' }],
    pass: [{ validator: validatorPassword, required: true, trigger: 'blur' }],
    pass2: [
      { validator: compareToFirstPassword, required: true, trigger: 'blur' },
    ],
    email: [
      {
        required: true,
        message: 'Please input email address',
        trigger: 'blur',
      },
      {
        type: 'email',
        message: 'Please input correct email address',
        trigger: ['blur'],
      },
    ],
  },
})
const submitForm = formEl => {
  if (!formEl) return
  formEl.validate(valid => {
    if (valid) {
      // 检查验证码是否已填写
      if (!registerData.emailRender) {
        ElMessage({
          message: '请先获取并填写邮箱验证码！',
          type: 'warning',
        })
        return false
      }
      loading.value = true
      const data = {
        id: registerData.stuNum,
        name: registerData.stuName,
        password: md5(registerData.pass),
        email: registerData.email,
        domain: registerData.domain[0],
        phone: registerData.phone,
        schoolMajor: registerData.schoolMajor,
      }
      registerUser(registerData.emailRender, data)
        .then(res => {
          if (res.data.success) {
            active.value = 2 // 注册完成步骤
            ElMessage({
              message: '注册成功,等待审核 !',
              type: 'success',
            })
          } else {
            ElMessage({
              message: res.data.msg || '注册失败，请重试',
              type: 'error',
            })
          }
          loading.value = false
        })
    } else {
      active.value = 0 // 回到填写信息步骤
      ElMessage({
        message: '请完善信息 !',
        type: 'error',
      })
      return false
    }
  })
}
const uploadCode = (e, formEl) => {
  e.preventDefault()
  // if (formEl.validateField('email'))
  formEl.validateField('email', isValid => {
    if (isValid) {
      active.value = 1 // 邮箱验证步骤
      registerData.setSendStatus = true
      let time = 60
      const clearnTime = setInterval(() => {
        time--
        if (time === 0) {
          clearInterval(clearnTime)
          registerData.text = '重新发送'
          registerData.setSendStatus = false
        } else {
          registerData.text = `${time}s后重新发送`
        }
      }, 1000)
      const params = {
        email: registerData.email,
      }
      postCode(base.uploadCode, params.email)
        .then(() => {})
        .catch(() => {
          // clearInterval(clearnTime)
          // helloData.sendEmail = '重新发送'
          // helloData.sendStatus = false
        })
      ElMessage({
        type: 'success',
        message: '发送成功,请查看邮箱 !!!',
      })
    }
  })
}

const myWatch = formEl => {
  if (!formEl) return
  formEl.validate(valid => {
    if (valid) {
      active.value = 1
    } else {
      active.value = 0
    }
  })
}

// 验证姓名
function validatorName(rule, value, callback) {
  if (value && value.length > 0 && value.length < 10) {
    callback()
  } else {
    callback('姓名控制在10个汉字以内')
  }
}

// 验证账号
function validatorId(rule, value, callback) {
  const treg = /^[0-9]\d*$|^0$/
  if (value && treg.test(value) === true && value.length === 12) {
    callback()
  } else {
    callback('请输入12位学号')
  }
}

// 验证手机号
function validatorIdPhone(rule, value, callback) {
  const treg = /^[0-9]\d*$|^0$/
  if (value && treg.test(value) === true && value.length === 11) {
    callback()
  } else {
    callback('请输入11位手机号')
  }
}

// 密码验证
function validatorPassword(rule, value, callback) {
  const patt = /(?=.*\d)(?=.*[a-zA-Z])^.{6,20}$/
  if (patt.test(value) && value) {
    callback()
  } else {
    callback('密码需要在6-20位之间并包含字母和数字')
  }
}

function compareToFirstPassword(rule, value, callback) {
  if (value && value !== registerData.pass) {
    callback('请确保两次密码输入一致')
  } else {
    callback()
  }
}

const querySearch = (value, cb) => {
  let autoCompleteResult
  if (!value || value.indexOf('@') >= 0) {
    autoCompleteResult = []
  } else {
    autoCompleteResult = [
      '@gmail.com',
      '@163.com',
      '@qq.com',
      '@aliyun.com',
    ].map(domain => `${value}${domain}`)
  }
  myWatch()
  cb(autoCompleteResult)
}
const handleSelect = item => {
  registerData.email = item
}
const resetForm = formEl => {
  if (!formEl) return
  formEl.resetFields()
}

const goToLogin = () => {
  router.push('/login')
}
</script>

<style scoped lang="less">
.register-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #409eff 0%, #337ecc 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  box-sizing: border-box;
}

.register-card {
  width: 100%;
  max-width: 800px;
  border-radius: 16px;
  overflow: hidden;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.1);

  :deep(.el-card__body) {
    padding: 40px;
  }
}

.register-header {
  text-align: center;
  margin-bottom: 30px;

  .register-title {
    font-size: 28px;
    font-weight: 600;
    color: #303133;
    margin: 0 0 10px 0;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 12px;

    .title-icon {
      font-size: 32px;
      color: #409eff;
    }
  }

  .register-subtitle {
    color: #909399;
    font-size: 16px;
    margin: 0;
  }
}

.register-steps {
  margin: 30px 0 40px 0;

  :deep(.el-step__title) {
    font-size: 14px;
    font-weight: 500;
  }
}

.register-form {
  .el-divider {
    margin: 30px 0 25px 0;

    :deep(.el-divider__text) {
      background-color: #fff;
      padding: 0 20px;
      color: #606266;
      font-weight: 500;
      font-size: 16px;
      display: flex;
      align-items: center;
      gap: 8px;
    }
  }

  .el-form-item {
    margin-bottom: 24px;

    :deep(.el-form-item__label) {
      font-weight: 500;
      color: #606266;
    }

    :deep(.el-input__wrapper) {
      border-radius: 8px;
      transition: all 0.3s ease;

      &:hover {
        box-shadow: 0 0 0 1px #c0c4cc inset;
      }
    }

    :deep(.el-cascader) {
      .el-input__wrapper {
        border-radius: 8px;
      }
    }
  }
}

.verification-code-container {
  display: flex;
  gap: 12px;
  width: 100%;

  .verification-input {
    flex: 1;
  }

  .send-code-btn {
    border-radius: 8px;
    padding: 0 24px;
    white-space: nowrap;
    min-width: 120px;
  }
}

.email-suggestion {
  padding: 8px 0;
  color: #606266;
}

.form-actions {
  margin-top: 40px;
  text-align: center;

  .el-button {
    border-radius: 8px;
    padding: 12px 32px;
    font-weight: 500;
    min-width: 120px;

    &.submit-btn {
      background: linear-gradient(135deg, #409eff 0%, #36a3f7 100%);
      border: none;
      box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 6px 16px rgba(64, 158, 255, 0.4);
      }
    }

    &.reset-btn {
      margin-left: 16px;
      border-color: #dcdfe6;
      color: #606266;

      &:hover {
        border-color: #c0c4cc;
        color: #409eff;
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .register-container {
    padding: 10px;
  }

  .register-card {
    :deep(.el-card__body) {
      padding: 20px;
    }
  }

  .register-header {
    .register-title {
      font-size: 24px;
    }
  }

  .register-form {
    :deep(.el-form-item__label) {
      text-align: left !important;
    }
  }

  .verification-code-container {
    flex-direction: column;

    .send-code-btn {
      width: 100%;
    }
  }

  .form-actions {
    .el-button {
      width: 100%;
      margin: 8px 0 0 0 !important;
    }
  }
}

// 动画效果
.register-card {
  animation: slideInUp 0.6s ease-out;
}

@keyframes slideInUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

// 表单验证状态样式优化
:deep(.el-form-item.is-error) {
  .el-input__wrapper {
    box-shadow: 0 0 0 1px #f56c6c inset;
  }
}

:deep(.el-form-item.is-success) {
  .el-input__wrapper {
    box-shadow: 0 0 0 1px #67c23a inset;
  }
}

// 登录链接样式
.login-link {
  text-align: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #f0f0f0;
}

.login-text {
  color: #909399;
  font-size: 14px;
  margin-right: 8px;
}

.login-btn {
  color: #409eff;
  font-weight: 500;
  padding: 0;
  font-size: 14px;

  &:hover {
    color: #337ecc;
    text-decoration: underline;
  }
}
</style>
